<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<style>
  .layui-table-cell {
    overflow: visible;
  }
  
  .layui-table-box {
    overflow: visible;
  }
  
  .layui-table-body {
    overflow: visible;
  }
  
  /* 设置下拉框的高度与表格单元相同 */
  td .layui-form-select {
    margin-top: -10px;
    margin-left: -15px;
    margin-right: -15px;
  }
  
  .fieldTable {
    padding-left: 10px;
    padding-right: 10px;
  }

  .layui-table-cell{
    display:table-cell;
    vertical-align: middle;
  }
</style>
<div class="layui-row">
  <div class="layui-col-md6 fieldTable">
    <fieldset class="layui-elem-field layui-field-title">
      <legend>默认配置</legend>
    </fieldset>
    <table
      class="layui-hide"
      id="fieldTable"
      lay-filter="fieldTableFilter"></table>
  </div>
  <div class="layui-col-md6 fieldTable">
    <fieldset class="layui-elem-field layui-field-title">
      <legend>自定义配置</legend>
    </fieldset>
    <table
      class="layui-hide"
      id="customTable"
      lay-filter="customTableFilter"></table>
  </div>
</div>
<script src="/util/utils.js"></script>

<script
  type="text/html"
  id="customTableToolbar">
  <div class="layui-btn-group ">
    <button
      type="button"
      class="layui-btn layui-btn-xs"
      lay-event="addCustom">
      添加字段
    </button>
    <button
      type="button"
      class="layui-btn layui-btn-xs layui-btn-normal"
      lay-event="saveCustom">
      保存
    </button>
  </div>
</script>

<script
  type="text/html"
  id="templateFieldBar">
  <a
    class="layui-btn layui-btn-danger layui-btn-xs"
    lay-event="del">删除</a>
</script>


<script th:inline="javascript">
  var templateId = [[${templateId}]]
  var defaultOptions = [[${defaultOptions}]]
  layui.use(['form', 'table'], function () {
    var $ = layui.$,
      table = layui.table,
      form = layui.form,
      fieldTableData = defaultOptions.map(item => {
        return {
          fieldKey: item.value,
          fieldValue: item.label,
          example: item.example
        }
      })

    var tableInit = table.render({
      id: 'fieldTable',
      elem: '#fieldTable',
      // toolbar: '#fieldTableToolbar',
      defaultToolbar: [''],
      cols: [
        [
          {
            field: 'fieldKey',
            title: '模版内名称',
            width: '30%'
          },
          {
            field: 'fieldValue',
            title: '对应名称',
            width: '30%'
          },
          {
            field: 'example',
            title: '例子',
            width: '40%',
            templet: function (d) {
              if (isJsonString(d.example)) {
                return Object.keys(JSON.parse(d.example)).map(item => {
                  return '<div>' + item + ':' + JSON.parse(d.example)[item] + '</div>'
                }).join("")
              } else {
                return d.example
              }
            }
          }
        ]
      ],
      data: fieldTableData
    })

    var customTableData = []
    var defaultData = []

    var customTable = table.render({
      id: 'customTable',
      elem: '#customTable',
      toolbar: '#customTableToolbar',
      where: {
        templateId: templateId
      },
      defaultToolbar: [''],
      cols: [
        [
          {
            field: 'fieldKey',
            title: '自定义Key',
            edit: true,
          },
          {
            field: 'fieldValue',
            title: '自定义Value',
            edit: true
          },
          {
            title: '操作',
            templet: '#templateFieldBar'
          }
        ]
      ],
      data: []
    })

    getListData()

    function getListData() {
      $.get('/code/template/field/list', {templateId: templateId}, function (response) {
        defaultData = response.data
        customTable.reload({
          data: defaultData.concat(customTableData)
        })
      })
    }

    //监听头工具栏事件
    table.on('toolbar(customTableFilter)', function (obj) {
      console.log(obj.config.data)
      var checkStatus = table.checkStatus(obj.config.id),
        data = checkStatus.data //获取选中的数据
      switch (obj.event) {
        case 'addCustom':
          console.log(templateId)
          customTableData.push({
            templateId: templateId,
            fieldKey: '请输入',
            fieldValue: '请输入'
          })
          customTable.reload({
            data: defaultData.concat(customTableData)
          })
          break
        case 'saveCustom':
          $.ajaxSetup({
            traditional: true,
            contentType: 'application/json;charset=utf-8'
          })

          //向服务端发送删除指令
          console.log(obj.config.data)
          $.post('/code/template/field', JSON.stringify(obj.config.data), function (response) {
            layer.msg(response.data, {
              time: 1000,
              icon: 1
            })
            getListData()
            customTableData = []
            customTable.reload({
              data: defaultData.concat(customTableData)
            })
          })
          break
        case 'delete':
          if (data.length === 0) {
            layer.msg('请选择一行')
          } else {
          }
          break
      }
    })


    //监听行工具事件
    table.on('tool(customTableFilter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data, //获得当前行数据
        layEvent = obj.event //获得 lay-event 对应的值
      if (layEvent === 'del') {
        if (data.id) {
          layer.confirm('真的删除行么', function (index) {
            obj.del() //删除对应行（tr）的DOM结构
            layer.close(index)
            //向服务端发送删除指令
            $.ajax({
              url: '/code/template/field/' + data.id,
              type: 'DELETE',
              success: function (response) {
                layer.msg(response.data, {
                  time: 1000,
                  icon: 1
                })
                getListData()
                customTable.reload({
                  data: defaultData.concat(customTableData)
                })
              }
            })
          })
        } else {
          obj.del() //删除对应行（tr）的DOM结构
          customTableData = customTableData.filter(item => {
            return !(item.fieldKey === data.fieldKey && item.templateId === data.templateId && item.fieldValue === data.fieldValue)
          })
          getListData()
          customTable.reload({
            data: defaultData.concat(customTableData)
          })
        }
      }
    })

  })


</script>
</html>
